<template>
  <div class="page-atlasList">
    <filter-view @update-list="() => getArticleList()" />
    <a-table
      id="sortTable"
      :row-selection="{ selectedRowKeys: statusState.selectedRowKeys, onChange: onSelectChange }"
      row-key="article_id"
      :columns="columns"
      :data-source="state.articleList"
      :loading="state.loading"
      :pagination="false"
      :scroll="{ x: 1500 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'article_album'">
          <a-tooltip placement="top" color="#fff" v-if="record && record.article_album.length > 0">
            <template #title>
              {{ getAlbumName(record.article_album) }}
            </template>
            <div class="ellipsis-text">
              {{ getAlbumName(record.article_album) }}
            </div>
          </a-tooltip>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'article_name'">
          <a-tooltip placement="top" color="#fff" v-if="record.article_name">
            <template #title>
              {{ record.article_name }}
            </template>
            <div class="ellipsis-text">{{ record.article_name }}</div>
          </a-tooltip>
          <span v-else>-</span>
        </template>
        <template v-if="column.key === 'article_cover'">
          <a-image
            width="37.82px"
            height="48px"
            class="w-[-webkit-fill-available] object-contain"
            :src="getIcon(record)"
            :fallback="defaultImage"
          />
        </template>
        <template v-else-if="column.key === 'article_categ_name'">
          <a-tooltip placement="top" color="#fff">
            <template #title>
              {{ getCategName(record) }}
            </template>
            <div class="ellipsis-text">
              {{ getCategName(record) || '-' }}
            </div>
          </a-tooltip>
        </template>
        <template v-else-if="column.key === 'article_price_type'">
          <span>
            {{ getArticleType(record) || '-' }}
          </span>
        </template>
        <template v-else-if="column.key === 'updated_at'">
          <span>
            {{ formatToDateTime(+record.updated_at * 1000) }}
          </span>
        </template>
        <template v-else-if="column.key === 'article_popularity'">
          <span>
            {{ formatNumber(record.article_popularity) }}
          </span>
        </template>
        <template v-else-if="column.key === 'article_status'">
          <span>
            <a-switch
              v-model:checked="record.article_status"
              :checkedValue="1"
              :unCheckedValue="2"
              @change="(checked:any) => editStatus(checked, record)"
            />
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a style="color: #0083ff" @click="updateArticle(record.article_id)">编辑</a>
            <a-divider type="vertical" />
            <a style="color: #0083ff" @click="deleteArticle(record.article_id)"> 删除 </a>
          </span>
        </template>
      </template>
      <!-- 删除对话框 -->
    </a-table>
    <a-pagination
      @change="handlePaginationChange"
      show-size-changer
      :defaultPageSize="10"
      :pageSizeOptions="['10', '20', '50', '100']"
      :show-total="(total:number)=>`共${total}条`"
      :total="queryState.total"
    />
    <modal-view
      title="提示"
      v-model:visible="deleteVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="deleteConfirm"
      @cancel="deleteCancel"
    >
      <span>确定要删除该文章吗</span>
    </modal-view>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, computed, inject } from 'vue'
import { message } from 'ant-design-vue'
import { formatNumber, formatToDateTime } from '@/utils/format'
import FilterView from './components/FilterView.vue'
import { column, PRICE_TYPE } from './dataSource'
import type { ArticleListData, IAlbum } from '@/types/site/article/articleList'
import ModalView from '@/components/components/modal/ModalView.vue'
import { articleListState, statusState } from './state'
import router from '@/router'
import apis from '@/apis'
import defaultImage from '@/assets/icon/defaultImage.png'
const {
  site: { article_list, edit_status, del_article }
} = apis
const columns = ref(column)
const deleteVisible = ref(false)
const deleteId = ref('') //删除行id
const imageDomain = inject('imageDomain') as any
console.log('imageDomain: ', imageDomain)
const baseUrl = computed(() => imageDomain.article_cover || window.location.origin + '/')
console.log('baseUrl: ', baseUrl)
type Key = string
const state = reactive<{ loading: boolean; articleList: ArticleListData[] }>({
  loading: false,
  articleList: [] as ArticleListData[]
})
const queryState = reactive({
  offset: 0, // 默认当前页数
  limit: 10, // 默认当前页显示数据的大小
  total: 0 // 总数，必须先有
})
//根据类型获取图片
const getIcon = computed(() => (item: ArticleListData) => {
  if (+item.article_cover_type == 1) return baseUrl.value + item.article_cover
  return item.article_cover
})
//获取拼接专辑名字
const getAlbumName = computed(() => (objs: IAlbum[]) => {
  var idsStr = objs
    .map((obj) => {
      return obj.album_name
    })
    .join(',')
  return idsStr
})
/**
 * 分页改变事件
 */
const handlePaginationChange = (size: number, limit: number) => {
  queryState.limit = limit
  queryState.offset = (size - 1) * limit
  getArticleList()
}
const getArticleList = () => {
  state.loading = true
  console.log('getActiveList')
  // 更新列表接口
  const params = {
    ...articleListState,
    ...queryState
  }
  if (!params.article_id) params.article_id = undefined
  article_list(params)
    .then((res: any) => {
      console.log('图集列表: ', res)
      state.articleList = res?.articles ?? []
      queryState.total = +res?.total ?? 0
      state.loading = false
      //处理下一页，第一条删除问题
      if (queryState.offset >= (res?.articles ?? 0) && queryState.total != 0) {
        queryState.offset -= queryState.limit
        getArticleList()
      }
    })
    .catch(() => {
      state.loading = false
    })
}
const onSelectChange = (rowKeys: Key[]) => {
  console.log('selectedRowKeys changed: ', rowKeys)
  statusState.selectedRowKeys = rowKeys
}
//删除文章
const deleteArticle = (id: string) => {
  console.log(id, 'id')
  deleteId.value = id
  deleteVisible.value = true
}
//更新文章
const updateArticle = (id: string) => {
  router.push({ name: 'EditArticle', query: { id } })
}
//获取分类名
const getCategName = computed(() => (record: ArticleListData) => {
  if (record.article_categ_name && record.article_subcateg_name) {
    return record.article_categ_name + '/' + record.article_subcateg_name
  } else if (record.article_categ_name && !record.article_subcateg_name) {
    return record.article_categ_name
  } else if (!record.article_categ_name && record.article_subcateg_name) {
    return record.article_subcateg_name
  } else {
    return '-'
  }
})
const editStatus = (checked: number, row: ArticleListData) => {
  const data = {
    type: 4,
    status: checked,
    id: [row.article_id]
  }
  edit_status(data).then(() => {
    message.success(checked === 1 ? '启用成功' : '禁用成功')
    getArticleList()
  })
}
/**
  删除影片对话框事件
 */
const deleteConfirm = (value: any) => {
  del_article({ article_id: [deleteId.value] }).then(() => {
    message.success('删除文章成功')
    deleteVisible.value = value
    getArticleList()
  })
}
const deleteCancel = () => {
  deleteVisible.value = false
}
//获取收费状态
const getArticleType = computed(() => (item: any) => {
  if (item.article_price_type === 1) {
    return '免费'
  } else {
    return PRICE_TYPE[item.article_price_type] + '-' + item.article_price + '金币'
  }
})
onMounted(() => {
  getArticleList()
})
</script>
<style lang="less">
.ant-tooltip-inner {
  color: #5e5e5e !important;
}
</style>
<style lang="less" scoped>
.page-atlasList {
  padding-top: 6px;
  box-sizing: border-box;

  :deep(.ant-table-thead > tr > th) {
    color: #262626;
    font-weight: 500;
  }

  :deep(
      .ant-table-thead
        > tr
        > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not(
          [colspan]
        )::before
    ) {
    width: 0;
  }

  :deep(.ellipsis-text) {
    max-width: 154px !important;
    white-space: nowrap;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: pointer;
  }
}
</style>
